//
//  YCApiProxy.swift
//  YCNetworking
//
//  Created by YC on 2017/3/7.
//  Copyright © 2017年 YC. All rights reserved. mail:yangchong364@qq.com
//

import UIKit
import Alamofire
import OurTools

typealias YCCallback = (_ response: YCURLResponse) -> Void

class YCApiProxy {
    static let shared = YCApiProxy()
    
    private var dispatchTable = [Int :  URLSessionTask]()
    private var sessionManager: SessionManager
    
    private init() {
        let configuration = URLSessionConfiguration.default
        self.sessionManager = Alamofire.SessionManager(configuration: configuration)
        
    }
    
    func callGet(with params: Dictionary<String,Any>, serviceIdentifier: String, methodName: String, success: @escaping YCCallback, fail: @escaping YCCallback ) -> Int {
        
        let request = YCRequestGenerator.shared.generateGetRequest(with: serviceIdentifier, requestParams: params, methodName: methodName)
        
        let requestId = self.callApi(with: request, success: success, fail: fail)
        
        return requestId
    }
    
    func callPost(with params: Dictionary<String,Any>, serviceIdentifier: String, methodName: String, success: @escaping YCCallback, fail: @escaping YCCallback ) -> Int {
        
        let request = YCRequestGenerator.shared.generatePostRequest(with: serviceIdentifier, requestParams: params, methodName: methodName)
        
        let requestId = self.callApi(with: request, success: success, fail: fail)
        
        return requestId
    }
    
    func callPut(with params: Dictionary<String,Any>, serviceIdentifier: String, methodName: String, success: @escaping YCCallback, fail: @escaping YCCallback ) -> Int {
        let request = YCRequestGenerator.shared.generatePutRequest(with: serviceIdentifier, requestParams: params, methodName: methodName)
        
        let requestId = self.callApi(with: request, success: success, fail: fail)
        
        return requestId
    }
    
    func callDelete(with params: Dictionary<String,Any>, serviceIdentifier: String, methodName: String, success: @escaping YCCallback, fail: @escaping YCCallback ) -> Int {
        let request = YCRequestGenerator.shared.generateDeleteRequest(with: serviceIdentifier, requestParams: params, methodName: methodName)
        
        let requestId = self.callApi(with: request, success: success, fail: fail)
        
        return requestId
    }
    
    func cancelRequest(with requestID: Int) {
        let requestOperation = self.dispatchTable[requestID]
        requestOperation?.cancel()
        self.dispatchTable.removeValue(forKey: requestID)
    }
    
    func cancelRequest(with requestIDList: Array<Int>) {
        for requestID in requestIDList {
            self.cancelRequest(with: requestID)
        }
    }
    
    func callApi(with request: URLRequest, success: @escaping YCCallback, fail: @escaping YCCallback) -> Int {
        
        let dataRequest = self.sessionManager.request(request)
        
        if let dataTask = dataRequest.task {
            let requestId = dataTask.taskIdentifier
            self.dispatchTable[requestId] = dataTask
            
            dataRequest.responseJSON { (response) in
                self.dispatchTable.removeValue(forKey: requestId)
                
                let responseString = String(data: response.data!, encoding: .utf8)
                
                PrintBlue("\n请求地址:\(String(describing: request.url))")
                PrintBlue("参数:\(try! JSONSerialization.jsonObject(with: request.httpBody!, options: .allowFragments))")
                PrintBlue("返回数据:\(String(describing: response.result.value))")
                
                switch response.result {
                case .success:
//                    YCLogger.logDebugInfo(with: response.response , responseString: responseString!, request: request, error: nil)
                    let ycResponse = YCURLResponse(responseString: responseString!, requestId: requestId, request: request, responseData: response.data, status: .success)
                    success(ycResponse)
                    
                case .failure(let error):
//                    YCLogger.logDebugInfo(with: response.response , responseString: responseString!, request: request, error: error as NSError?)
                    
                    let ycResponse = YCURLResponse(responseString: responseString!, requestId: requestId, request: request, responseData: response.data, error: error as NSError!)
                    fail(ycResponse)
                }
            }
            
            dataTask.resume()
            
            return requestId
        }
        
        return 0
    }
    
//    func test() -> Int{
//        let urlString = "https://webapi.ltools.cn/api/SystemLogin/Login"
//        
//        let headers = ["Version" : "3.2.0",
//                       "Platform" : "2"]
//        
//        let parameters = ["forced":"0",
//                          "isAutoLogin":"0",
//                          "name":"10622",
//                          "password":"2wr9sBEogE6DVRcHG8fiLA==",
//                          "tag":"614074524DAA40CAA144D5F96C4F07D5_2"]
//        
//        
//        let dataRequest = Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
//        
//        if let dataTask = dataRequest.task {
//            let requestId = dataTask.taskIdentifier
//            self.dispatchTable[requestId] = dataTask
//            
//            dataRequest.validate().responseJSON { (response) in
//                self.dispatchTable.removeValue(forKey: requestId)
//                
//                switch response.result {
//                case .success:
//                    print(response.result.value as Any)
//                case .failure(let error):
//                    print("\(error)")
//                }
//            }
//            
//            dataTask.resume()
//            
//            return requestId
//        }
//        
//        return 0
//    }
}
